<?php

namespace common\components\office\grid;

use Yii;
use yii\base\InvalidConfigException;
use common\helpers\ArrayHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * GridExcel
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class MultipleGridExcel extends GridExcel {

    /**
     * @var array
     */
    public $models = [];

    /**
     * Initializes the grid view.
     * This method will initialize required property values and instantiate [[columns]] objects.
     */
    public function init() {
        if (empty($this->models)) {
            throw new InvalidConfigException('The "models" property must be set.');
        }
        $this->models = (array) $this->models;
        $this->createSpreadSheet();
        $this->initSheets();
    }

    /**
     * @return Spreadsheet
     */
    public function renderSheet() {
        return $this->getSpreadSheet();
    }

    /**
     * Creates column objects and initializes them.
     */
    protected function initSheets() {
        $spreadsheet = $this->getSpreadSheet();
        $i = 0;
        foreach ($this->models as $options) {
            if ($i) {
                $activeSheet = $spreadsheet->createSheet();
            } else {
                $activeSheet = $this->getActiveSheet();
            }
            $sheetName = ArrayHelper::remove($options, 'sheetName');
            $gridClass = ArrayHelper::remove($options, 'gridClass', GridExcel::class);
            $activeSheet->setTitle($sheetName);
            $spreadsheet->setActiveSheetIndexByName($sheetName);
            $options['class'] = $gridClass;
            $options['excelSpreadSheet'] = $spreadsheet;
            $options['protection'] = $this->protection;
            $worksheet = Yii::createObject($options);
            $worksheet->run();
            $i++;
        }
    }

}
